﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EF4.Core.Service;
using EF4.Core.Models.Entities;
using EF4.Core.Repository;
using EF4.Core.IoC;
using System.Linq.Expressions;
using EF4.Model.Entities;
using EF4.Core;
using EF4.Core.Logger;

namespace EF4.Services
{
    public class GenericService<T> where T : EntityBase/*: IService<T> where T : EntityBase*/
    {
        private IGenericRepository<T> reposity;
        // use for transaction
        private  UnitOfWork worker;
        IRepositoryContext context;

        public UnitOfWork  Worker { get {return worker;} }
        public GenericService()
        {
            reposity = IoCContainer.Current.GetInstance<IGenericRepository<T>>();
            context = IoCContainer.Current.GetInstance<IRepositoryContext>();
            worker = new UnitOfWork(context);

        }
        public static IGenericRepository<T>  GetInsance()
        {
            //if (reposity == null)
            //{
            //    //reposity = IoCWorker.Resolve<IGenericRepository<T>>();
            //    reposity = IoCContainer.Current.GetInstance<IGenericRepository<T>>(); 
            //}
            //return reposity;
            return null;
        }
         
        public  void Add(T entity)
        {
            try
            {
                reposity.Add(entity);
                worker.SaveChanges();
            }
            catch (Exception ex) {
                Logger.Error(ex.Message);
            }
        }
        public  T GetById(int id)
        {
            return reposity.Get(id);
        }
        public  T GetByPK(string EntityKey, object PKValue)
        {
            return reposity.Get(EntityKey, PKValue);
        }
        public  List<T> AllItems()
        {
            return reposity.GetAll();
        }
        public  void Delete(T entity)
        {
            reposity.Delete(entity);
            worker.SaveChanges();
        }
        public  IPagedList<T> GetListPaged(int pageIndex, int pageSize, string orderBy, OrderDirections direction)
        {
            return reposity.GetListPaged(pageIndex, pageSize, orderBy, direction);
        }
        public  IPagedList<T> GetListPaged(int pageIndex, int pageSize, string orderBy)
        {
            return reposity.GetListPaged(pageIndex, pageSize, orderBy, OrderDirections.ASC);
        }
        public  void Update(T entity)
        {
            reposity.Update(entity);
            worker.SaveChanges();
        }
        public  int Count
        {
            get {
                return reposity.Count();
            }
        }

    }
}
